package org.lsp.io.files;

import java.io.File;
import java.util.HashMap;
import java.util.concurrent.Semaphore;

import org.lsp.io.logger.SysLogger;

public abstract class FileLocker {

	private static final HashMap<File, Semaphore> locksMap = new HashMap<>();

	public static final void getLock(final File file) {
		if (!FileLocker.locksMap.containsKey(file)) {
			FileLocker.locksMap.put(file, new Semaphore(1, Boolean.TRUE));
		}
		final Semaphore target = FileLocker.locksMap.get(file);
		synchronized (target) {
			try {
				FileLocker.locksMap.get(file).acquire();
			} catch (final InterruptedException e) {
				SysLogger.log(e, "ERR0", SysLogger.Level.CRASH);
			}
			if (file.isDirectory()) {
				for (final File f : file.listFiles()) {
					if (f.isDirectory()) {
						FileLocker.getLock(f);
					}
				}
			}
		}
	}

	public static final void releaseLock(final File file) {
		final Semaphore target = FileLocker.locksMap.get(file);
		if (file.isDirectory()) {
			for (final File f : file.listFiles()) {
				if (f.isDirectory()) {
					FileLocker.releaseLock(f);
				} else {
					target.release();
				}
			}
		}
		target.release();
	}
}
